
#include "userConfig.h"
#include "Serial.h"
#include <xc.h>
#include <libpic30.h>
#include <stdlib.h>
int __psv__ __attribute__((space(eedata), aligned(_EE_ROW))) EELowTemperatureThreshold;
int __psv__ __attribute__((space(eedata), aligned(_EE_ROW))) EEHighTemperatureThreshold;
int __psv__ __attribute__((space(eedata), aligned(_EE_ROW))) EECANAddress;
int __psv__ __attribute__((space(eedata), aligned(_EE_ROW))) EEExternalNodeCount;

static int LowTemperatureThreshold;
static int HighTemperatureThreshold;
static unsigned char CANAddress;
static int ExternalNodeCount;

static void SetVariablesFromEEPROM();
static void WriteEEPROMValue(_prog_addressT destination, int value);

void InitializeUserConfig()
{
    SetVariablesFromEEPROM();
}

void SetVariablesFromEEPROM()
{
    LowTemperatureThreshold = EELowTemperatureThreshold;
    HighTemperatureThreshold = EEHighTemperatureThreshold;
    CANAddress = EECANAddress;
    ExternalNodeCount = EEExternalNodeCount;
}

void PrintUserConfig()
{
    PutString("User Config is:\r");
    PutString("Low Temperature Threshold: ");
    char buffer[10];
    itoa(buffer, LowTemperatureThreshold, 10);
    PutString(buffer);
    PutString("\rHigh Temperature Threshold: ");
    itoa(buffer, HighTemperatureThreshold, 10);
    PutString(buffer);
    PutString("\r CAN Address: ");
    itoa(buffer, CANAddress, 10);
    PutString(buffer);
    PutString("\rExternal Node Count: ");
    itoa(buffer, ExternalNodeCount, 10);
    PutString(buffer);
    Putchar('\r');
    Putchar('\r');
}

void WriteEEPROMValue(_prog_addressT destination, int value)
{
    _erase_eedata(destination, _EE_WORD);
    _wait_eedata();
    _write_eedata_word(destination, value);
    _wait_eedata();
}

void SetLowTemperatureThreshold(int temperature)
{
    LowTemperatureThreshold = temperature;
    WriteEEPROMValue(__builtin_tbladdress(&EELowTemperatureThreshold), temperature);
}

int GetLowTemperatureThreshold()
{
    return LowTemperatureThreshold;
}

void SetHighTemperatureThreshold(int temperature)
{
    HighTemperatureThreshold = temperature;
    WriteEEPROMValue(__builtin_tbladdress(&EEHighTemperatureThreshold), temperature);
}

int GetHighTemperatureThreshold()
{
    return HighTemperatureThreshold;
}

void SetCANAddress(unsigned char address)
{
    CANAddress = address;
    WriteEEPROMValue(__builtin_tbladdress(&EECANAddress), address);
}

unsigned char GetCANAddress()
{
    return CANAddress;
}

void SetExternalNodeCount(int count)
{
    ExternalNodeCount = count;
    WriteEEPROMValue(__builtin_tbladdress(&EEExternalNodeCount), count);
}

int GetExternalNodeCount()
{
    return ExternalNodeCount;
}
